// logindialog.cpp
#include "logindialog.h"
#include "registerdialog.h"
#include "client_network.h"
#include "ui_login.h"
#include "request_sender.h"
#include <QPainter>
#include <QGraphicsDropShadowEffect>
#include <QSequentialAnimationGroup>
#include <QMouseEvent>
#include <QTimer>

LoginDialog::LoginDialog(RequestSender *requestSender,ClientNetwork *clientNet,QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::LoginDialog)
    , m_clientNetwork(clientNet)
    ,m_requestSender(requestSender)
{
    ui->setupUi(this);

    // 设置窗口无边框和透明背景
    setWindowFlags(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_TranslucentBackground);

    // 设置阴影效果
    QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect(this);
    shadow->setBlurRadius(20);
    shadow->setColor(QColor(0, 0, 0, 160));
    shadow->setOffset(0, 0);
    ui->mainWidget->setGraphicsEffect(shadow);

    // 设置圆角
    ui->mainWidget->setStyleSheet("QWidget#mainWidget{background: white; border-radius: 10px;}");

    // 设置输入框样式
    QString lineEditStyle = "QLineEdit {"
                            "border: 2px solid #e0e0e0;"
                            "border-radius: 5px;"
                            "padding: 8px;"
                            "font-size: 14px;"
                            "}"
                            "QLineEdit:focus {"
                            "border-color: #4a90e2;"
                            "}";

    ui->usernameEdit->setStyleSheet(lineEditStyle);
    ui->passwordEdit->setStyleSheet(lineEditStyle);
    ui->passwordEdit->setEchoMode(QLineEdit::Password);

    // 设置按钮样式和动画
    QString buttonStyle = "QPushButton {"
                          "background-color: #4a90e2;"
                          "color: white;"
                          "border: none;"
                          "border-radius: 5px;"
                          "padding: 10px;"
                          "font-weight: bold;"
                          "}"
                          "QPushButton:hover {"
                          "background-color: #3a7bc8;"
                          "}"
                          "QPushButton:pressed {"
                          "background-color: #2a6bb4;"
                          "}";

    ui->loginButton->setStyleSheet(buttonStyle);
    ui->registerButton->setStyleSheet(buttonStyle.replace("#4a90e2", "#50c9ba"));

    // 连接信号槽
    connect(ui->loginButton, &QPushButton::clicked, this, &LoginDialog::onLoginClicked);
    connect(ui->registerButton, &QPushButton::clicked, this, &LoginDialog::onRegisterClicked);
    connect(ui->closeButton, &QPushButton::clicked, this, &QDialog::reject);

    setFocusPolicy(Qt::StrongFocus);  // 确保对话框能接收键盘事件
    ui->usernameEdit->setFocus();     // 初始焦点放在输入框

    if (m_clientNetwork) {
        connect(m_clientNetwork, &ClientNetwork::loginResponseReceived,
                this, &LoginDialog::handleLoginResponse);
    }
}

LoginDialog::~LoginDialog()
{
    delete ui;
}

QString LoginDialog::username() const
{
    return ui->usernameEdit->text();
}

QString LoginDialog::password() const
{
    return ui->passwordEdit->text();
}

void LoginDialog::clearFields()
{
    ui->usernameEdit->clear();
    ui->passwordEdit->clear();
}

void LoginDialog::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        m_dragPosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    }
}

void LoginDialog::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton) {
        move(event->globalPos() - m_dragPosition);
        event->accept();
    }
}

void LoginDialog::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) {
        onLoginClicked();  // 直接调用登录逻辑
        event->accept();
    } else {
        QDialog::keyPressEvent(event);  // 其他按键交给父类处理
    }
}

void LoginDialog::paintEvent(QPaintEvent *event)
{
    // Q_UNUSED(event);

    // QPainter painter(this);
    // painter.setRenderHint(QPainter::Antialiasing);

    // // 绘制渐变色背景
    // QLinearGradient gradient(0, 0, width(), height());
    // gradient.setColorAt(0, QColor(100, 181, 246));
    // gradient.setColorAt(1, QColor(66, 165, 245));
    // painter.fillRect(rect(), gradient);
}

void LoginDialog::onLoginClicked()
{
    animateButton(ui->loginButton);

    // 获取输入的用户名和密码
    QString user = username();
    QString pwd = password();

    if (user.isEmpty() || pwd.isEmpty()) {
        ui->errorLabel->setText("用户名和密码不能为空");
        ui->errorLabel->setStyleSheet("color: red;");
        return;
    }

    // 显示正在登录状态
    ui->errorLabel->setText("正在登录...");
    ui->errorLabel->setStyleSheet("color: blue;");
    ui->loginButton->setEnabled(false);  // 禁用登录按钮防止重复点击

    // 通过发送器发送登录请求
    if(m_requestSender) {
        m_requestSender->sendLoginRequest(user, pwd);
    }
}

void LoginDialog::handleLoginResponse(const QJsonObject &response)
{
    // 重新启用登录按钮
    ui->loginButton->setEnabled(true);

    // 解析响应数据
    bool success = response["success"].toBool();
    QString message = response["message"].toString();
    QString token = response.value("token").toString();  // 使用value避免不存在的key导致崩溃

    if (success) {
        // 登录成功处理
        ui->errorLabel->setText("登录成功");
        ui->errorLabel->setStyleSheet("color: green;");

        // 保存token等信息（根据实际需求）
        // QSettings settings;
        // settings.setValue("auth_token", token);

        // 延迟一点点时间让用户看到成功消息
        QTimer::singleShot(500, this, [this]() {
            emit loginSuccess(username());
            accept();  // 关闭对话框
        });
    } else {
        // 登录失败处理
        ui->errorLabel->setText(message.isEmpty() ? "登录失败" : message);
        ui->errorLabel->setStyleSheet("color: red;");
    }
}

void LoginDialog::onRegisterClicked()
{
    animateButton(ui->registerButton);
    emit requestShowRegister();
}

void LoginDialog::animateButton(QWidget *button)
{
    QPropertyAnimation *animation = createButtonAnimation(button);
    animation->start(QPropertyAnimation::DeleteWhenStopped);
}

QPropertyAnimation *LoginDialog::createButtonAnimation(QWidget *target)
{
    QPropertyAnimation *animation = new QPropertyAnimation(target, "geometry");
    animation->setDuration(100);
    animation->setKeyValueAt(0, target->geometry());
    animation->setKeyValueAt(0.5, target->geometry().adjusted(-5, -5, 5, 5));
    animation->setKeyValueAt(1, target->geometry());
    return animation;
}
